import asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
# from django.urls import re_path
# from index.client_get_or_input_data import get_data  # 引入数据获取函数
from index.bs_control import *

class PV_DataConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        """ 处理 WebSocket 连接 """
        await self.accept()  # 接受连接
        print("Client connected")
        self.send_task = asyncio.create_task(self.send_data())  # 启动数据发送任务

    async def disconnect(self, close_code):
        """ 处理 WebSocket 断开 """
        print("Client disconnected")
        self.send_task.cancel()  # 取消数据发送任务

    async def send_data(self):
        """ 每秒获取数据并发送给客户端 """
        try:
            while True:
                pv = get_data("get_data")  # 获取数据
                data = {
                    'inverter_active_power': str(pv[14]),
                    'pv_active_power': str(pv[11]),
                    'storage_active_power': str(pv[25]),
                    'storage_soc': str(pv[19]),
                }
                # getspeed_on()
                # rate = read_speed()  # 获取基站速率数据
                # if rate is not None:
                #     data = {
                #         'inverter_active_power': str(pv[14]),
                #         'pv_active_power': str(pv[11]),
                #         'storage_active_power': str(pv[25]),
                #         'storage_soc': str(pv[19]),
                #         'DL_MAC': str(rate[0]),
                #         'DL_RLC': str(rate[1]),
                #         'UL_MAC': str(rate[2]),
                #         'UL_RLC': str(rate[3]),
                #     }
                # else:
                #     data = {
                #         'inverter_active_power': str(pv[14]),
                #         'pv_active_power': str(pv[11]),
                #         'storage_active_power': str(pv[25]),
                #         'storage_soc': str(pv[19]),
                #     }
                await self.send(text_data=json.dumps(data))  # 发送 JSON 数据
                await asyncio.sleep(1)  # 每秒发送一次
            # getspeed_on()
        except asyncio.CancelledError:
            pass  # 任务取消时不报错
